<script setup lang="ts">
import { message } from "@/utils/message";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css";
import axios from "axios";
import {
  nextTick,
  onBeforeUnmount,
  onMounted,
  ref,
  shallowRef,
  watch
} from "vue";

defineOptions({
  name: "WangEditor"
});

// 传值
const props = defineProps({
  modelValue: {
    type: String,
    default: ""
  },
  disable: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(["update:modelValue"]);

// 编辑器
const isInit = ref(false);
const editorContent = ref(props.modelValue);
const filePreUrl = localStorage.getItem("picurl");
const editorRef = shallowRef();
const mode = "default";
const toolbarConfig: any = { excludeKeys: "fullScreen" };
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    ["uploadImage"]: {
      server: "/",
      maxFileSize: 15 * 1024 * 1024,
      timeout: 60 * 1000,
      fieldName: "file",
      async customUpload(file: File, insertFn) {
        try {
          const response = await axios.post(
            "/erpPlatApi/common/upload",
            {
              file: file
            },
            {
              headers: {
                "Content-Type": "multipart/form-data",
                Accept: "application/json, text/plain, */*"
              }
            }
          );
          if (response.data.code == 200) {
            let imgUrl = filePreUrl + response.data.data;
            insertFn(imgUrl, file.name, imgUrl); // 插入图片，参数：图片 src、alt、href
          } else {
            message("上传文件异常！", { type: "error" });
          }
        } catch (error) {
          message("上传文件异常！" + error, { type: "error" });
          console.error("Error posting data:", error);
        }
      }
    },
    ["uploadVideo"]: {
      server: "/",
      maxFileSize: 25 * 1024 * 1024,
      timeout: 60 * 1000,
      fieldName: "file",
      async customUpload(file: File, insertFn) {
        try {
          const response = await axios.post(
            "/erpPlatApi/common/upload",
            {
              file: file
            },
            {
              headers: {
                "Content-Type": "multipart/form-data",
                Accept: "application/json, text/plain, */*"
              }
            }
          );
          if (response.data.code == 200) {
            let imgUrl = filePreUrl + response.data.data;
            insertFn(imgUrl);
          } else {
            message("上传文件异常！", { type: "error" });
          }
        } catch (error) {
          message("上传文件异常！" + error, { type: "error" });
          console.error("Error posting data:", error);
        }
      }
    }
  }
};

const handleCreated = editor => {
  editorRef.value = editor;
};

watch(
  () => props.modelValue,
  newValue => {
    if (newValue && !isInit.value) {
      isInit.value = true;
      editorContent.value = newValue;
    }
  },
  { immediate: true }
);

watch(
  () => editorContent,
  newValue => {
    emit("update:modelValue", newValue);
  },
  { immediate: true }
);

onMounted(() => {
  nextTick(() => {
    if (props.disable) {
      editorRef.value && editorRef.value.disable();
    }
  });
});

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
</script>
<template>
  <div class="wangeditor">
    <Toolbar
      v-if="!disable"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
      style="border-bottom: 1px solid #ccc"
    />
    <Editor
      v-model="editorContent"
      :defaultConfig="editorConfig"
      :mode="mode"
      style="height: 500px; overflow-y: hidden"
      @onCreated="handleCreated"
    />
  </div>
</template>
<style lang="scss" scoped></style>
